package com.yangming.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.yangming.common.base.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户认证
 * @author PengShuiMing
 * @create 2018-09-08
 **/
@Component
public class OauthUtil {
    private static final Logger logger = LoggerFactory.getLogger(OauthUtil.class);
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 微信开发者ID
     */
    @Value("${we.chat.app.id}")
    private String appId;
    /**
     * 微信开发者密码
     */
    @Value("${we.chat.secret}")
    private String secret;

    /**
     * 获取openId
     * @param code
     * @param request
     * @return
     */
    public String getOpenId(String code , HttpServletRequest request) {
        String openId = null;
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        logger.info("code=" + code);
        //发送请求
        ResponseEntity<String> body = restTemplate.getForEntity(url, String.class);
        logger.info("body=" + body.toString());
        JSONObject jsonObject = JSONObject.parseObject(body.getBody());
        if (jsonObject.containsKey("openid")) {
            openId = jsonObject.getString("openid");
            request.getSession().setAttribute(Constants.USER_OPEN_ID_KEY, openId);
        }
        return openId;
    }

    /**
     * 获取微信用户信息
     * @param code
     * @param request
     * @return
     */
    public JSONObject getWeChatInfo(String code , HttpServletRequest request) {
        JSONObject weChatInfo = null;
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        //发送请求
        ResponseEntity<String> body = restTemplate.getForEntity(url, String.class);
        logger.info("body=" + body.toString());
        JSONObject jsonObject = JSONObject.parseObject(body.getBody());
        if (jsonObject.containsKey("openid")) {
            String openId = jsonObject.getString("openid");
            String access_token = jsonObject.getString("access_token");
            request.getSession().setAttribute(Constants.USER_OPEN_ID_KEY, openId);
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            ResponseEntity<String> info = restTemplate.getForEntity(infoUrl, String.class);
            weChatInfo = JSONObject.parseObject(info.getBody());
        }
        return weChatInfo;
    }
}
